from google.appengine.ext.db import Query, Key
from plzkeepthat.models.models import Note, NoteTag, Tag
import logging

def get_notes_by_tag(tag, notelist, limit = 0, offset = 0):
    return [nt.note for nt in Query(NoteTag).filter("tag = ", tag).fetch(limit, offset)]

def is_valid_tag(tag, notelist):
    return Query(Tag).filter("notelist = ", notelist).filter("text = ", tag).count() > 0

def get_note_by_id(id, notelist):
    return Query(Note).filter("__key__ =", Key(id)).filter("noteList =", notelist).get()

def get_tags_for_note(note):
    logging.info(Query(NoteTag).filter("note = ", note).fetch(100))
    return [t.tag for t in Query(NoteTag).filter("note = ", note).fetch(100)]

def get_all_tags(notelist):
    return Query(Tag).filter("notelist = ", notelist).fetch(100)

def get_all_tag_note_links(note):
    return Query(NoteTag).filter("note = ", note).fetch(100)

def get_all_tag_note_links_for_tag(tag):
    limit = 1000
    i = 1
    all_links = []
    results = Query(NoteTag).filter("tag = ", tag).fetch(limit)

    while len(results) > 0:
        all_links += results
        results = Query(NoteTag).filter("tag = ", tag).fetch(limit, limit * i)
        i += 1
        logging.info(results)

    return all_links

def get_or_insert_tag_by_name(tagname, notelist):
    tag = Query(Tag).filter("text = ", tagname).filter("notelist = ", notelist).get()
    if tag is None:
        tag = Tag(text = tagname, notelist = notelist)
        tag.put()
    return tag


def save_note(note, tags, new = True):
    if new:
        notes = note.noteList
        notes.count += 1
        notes.put()
    else:
        for nt in get_all_tag_note_links(note):
            nt.delete()

    note.put()

    for tag in tags:
        link = NoteTag(note = note, tag = tag)
        link.put()

def delete_note(note):
    if note is not None:
        note.delete()
        delete_all_tags(note)
        return True
    else:
        return  False

def delete_note_by_id(id, notelist):
    return delete_note(get_note_by_id(id, notelist))

def delete_all_tags(note):
    for tl in get_all_tag_note_links(note):
        tag = tl.tag
        tl.delete()
        if len(get_all_tag_note_links_for_tag(tag)) == 0:
            tag.delete()
    return True

def get_all_notes_before(date):
    return Note.all().filter("created <= ", date)
